<template>
    <Upload
        :action="uploadData.host"
        :data="uploadData"
        accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-error="onError"
        :on-format-error="onFormatError"
        :on-exceeded-size="onExceededSize"
        :disabled="btnDisabled"
    >
        <Button
            :loading="btnDisabled"
            type="primary"
            icon="ios-cloud-upload-outline"
            >导入</Button
        >
    </Upload>
</template>

<script>
import uploadOss from '@/lib/upload-oss';
import { ElMessage } from 'element-plus';
const { getUploadToken, getFileKey } = uploadOss;

export default {
    data() {
        return {
            btnDisabled: false,
            uploadData: {
                host: ''
            }
        };
    },
    mounted() {
        getUploadToken(
            {
                moduleType: 'tempfile',
                publicRead: true
            },
            this
        ).then((res) => {
            const uploadData = res.data;
            uploadData.OSSAccessKeyId = uploadData.accessKeyId;

            this.uploadData = uploadData;
        });
    },
    methods: {
        beforeUpload(file) {
            this.btnDisabled = true;

            this.uploadData.key = getFileKey(
                this.uploadData.path,
                this.uploadData.signature,
                file.name
            );
        },
        onSuccess(response, file, fileList) {
            const url = this.uploadData.host + '/' + this.uploadData.key;

                G_transmit('importWord', {
                    message: false,
                    queries: {
                        url
                    }
                })
                .then((res) => {
                    if (res.success) {
                        this.$emit('to-import', res.data);
                    } else {
                        ElMessage.error(res.message || '导入失败');
                    }
                })
                .catch((err) => {
                    ElMessage.error(err.message || '导入失败');
                })
                .finally(() => {
                    this.btnDisabled = false;
                });
        },
        onError() {
            this.btnDisabled = false;
        },
        onFormatError() {},
        onExceededSize() {}
    }
};
</script>
